package com.situ.ymall.quartz;

import com.situ.ymall.service.OrderService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class QuartManager {

    //注入一个调度器
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private OrderService orderService;
    /*
    *   向调度器添加一个作业任务
    *
    * */
    public void addJob(String orderId){
        CleanOrderJob.orderService = orderService;

        // 1 - 创建一个 JobDetail       创建者模式:需要一个建造者模式，建造者根据设置的值创建需要的对象
        JobDetail jobDetail = JobBuilder
                .newJob(CleanOrderJob.class)
                .withIdentity(orderId,orderId)
                .usingJobData("orderId",orderId)
                .build();

        Date now = new Date();
        Date exeDate = new Date(now.getTime() + 30*60*1000);
        SimpleDateFormat sdf = new SimpleDateFormat("s m H * * ?");
        String  cron = sdf.format(exeDate);  // "s m H * * ?"
        System.err.println(cron);

        //  2 - 创建一个触发器
        Trigger trigger = TriggerBuilder
                .newTrigger()
                /*.forJob(jobDetail)*/
                .withIdentity("triggerName","triggerGroup")
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .endAt(new Date(exeDate.getTime() + 10*1000))
                .build();
        // 3 -调度任务
        try {

            scheduler.scheduleJob(jobDetail,trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
